﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ELearning.Wpf.UI
{
    using ELearning.Data.LearningDatasetTableAdapters;

    /// <summary>
    /// Interaction logic for wndNewPassword.xaml
    /// </summary>
    public partial class wndNewPassword : Window
    {
        private readonly long _userId;

        private readonly bool _promtOldPassword;

        private readonly string _oldPassword;

        public wndNewPassword(long userID, bool promtOldPassword)
        {
            _userId = userID;
            _promtOldPassword = promtOldPassword;
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.HideErrorLabels();
            UsersTableAdapter usersTableAdapter;

            if (_promtOldPassword)
            {
                usersTableAdapter = new UsersTableAdapter();
                var oldPassword = usersTableAdapter.GetPasswordHashByID(_userId);
                var inputPassword = MD5Helper.GetHashFromString(tb_OldPassword.Password);
                if (!oldPassword.SequenceEqual(inputPassword))
                {
                    lb_OldPasswordError.Visibility = Visibility.Visible;
                    usersTableAdapter.Dispose();
                    return;
                }
            }

            if (tb_NewPassword.Password.Trim() == string.Empty)
            {
                lb_IncorectConfirmation.Content = "Порожнi паролi забороненi";
                lb_IncorectConfirmation.Visibility = Visibility.Visible;
                return;
            }

            if (tb_NewPassword.Password != tb_NewPasswordRepeat.Password)
            {
                lb_IncorectConfirmation.Content = "Паролi не спiвпадають";
                lb_IncorectConfirmation.Visibility = Visibility.Visible;
                return;
            }

            usersTableAdapter = new UsersTableAdapter();
            usersTableAdapter.UpdatePasswordHash(MD5Helper.GetHashFromString(tb_NewPassword.Password), _userId);
            usersTableAdapter.Dispose();
            DialogResult = true;
        }

        private void HideErrorLabels()
        {
            this.lb_OldPasswordError.Visibility = Visibility.Hidden;
            this.lb_IncorectConfirmation.Visibility = Visibility.Hidden;
        }
    }
}
